import { ref, h, defineComponent } from "vue";
import { ElTable, ElTableColumn, ElPagination } from "element-plus";
import "./styles/Ctable.scss";
import { get as _get } from "lodash";
const tableProps = {
  columns: {
    type: Array,
    default: () => [],
  },
  data: {
    type: Array,
    default: () => [],
  },
  pagination: {
    type: Object,
    default: () => {},
  },
};
export default defineComponent({
  props: tableProps,
  setup(props: any, { attrs, slots, expose }: any) {
    const $slots = slots;
    const tableRef = ref<InstanceType<typeof ElTable>>();

    expose({
      tableRef,
    });

    return () =>
      h("div", { class: "c_table" }, [
        h(
          ElTable,
          {
            ref: tableRef,
            data: props.data,
            border: true,
            style: { width: "100%" },
            headerRowClassName: "table_demo",
            headerCellStyle: { background: "rgba(247, 248, 250, 1)" },
            key: Math.random().toString(),
            rowKey: (row: any) => row.id,
            // 透传支持使用原有功能
            ...attrs,
          },
          {
            default: () => {
              return props.columns.map((item: any, index: number) => {
                let itemProps = { ...item };
                // 只扩展了 render和renderTitle属性
                delete itemProps.render;
                delete itemProps.renderTitle;
                let slots: any = {};
                // 表格列注册了插槽并传递了插槽（插槽优先于渲染函数）
                if (item.slotName && $slots[item.slotName]) {
                  slots.default = (scope: any) => {
                    return $slots[item.slotName](scope.row);
                  };
                } else if (!["selection", "index"].includes(item.type)) {
                  slots.default = (scope: any) => {
                    return item.render && Object.keys(scope.row).length
                      ? item.render(scope.row)
                      : h("span", _get(scope.row, item.prop));
                  };
                }
                if (item.renderTitle) {
                  slots.header = (scope: any) => item.renderTitle(scope);
                }
                if (item.type == "index") {
                  console.log(Object.keys(slots));
                }
                return h(
                  ElTableColumn,
                  {
                    // 设置默认值
                    prop: item.prop,
                    label: item.label,
                    align: "center",
                    key: index,
                    //透传，同v-bind一样。 支持使用列原有功能
                    ...itemProps,
                  },
                  slots,
                );
              });
            },
            empty: () =>
              h("div", { class: "noData" }, [h("div", [h("div", "暂无数据")])]),
          },
        ),
        h("div", { class: "pagination" }, [
          h(ElPagination, { ...props.pagination }),
        ]),
      ]);
  },
});

